<?php


namespace App\Utils;


use App\Constants\AdminRoles;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use Hyperf\Utils\Context;
use Phper666\JWTAuth\Util\JWTUtil;
use Psr\Http\Message\ServerRequestInterface;

class Token
{
    // 获取token数据
    public static function getTokenData(): array
    {
        $request = Context::get(ServerRequestInterface::class);
        if (!JWTUtil::getToken($request)) {
            throw new BusinessException(ErrorCode::LOGIN_ERROR);
        }
        $tokenData = JWTUtil::getParserData($request);
        if (!$tokenData OR !isset($tokenData['id'])) {
            throw new BusinessException(ErrorCode::LOGIN_ERROR);
        }
        return $tokenData;
    }

    // APP会员ID
    public static function getMemberId()
    {
        $tokenData = self::getTokenData();
        return $tokenData['id'];
    }

    // 获取管理员或学校账号ID
    public static function getAdminOrSchoolID()
    {
        $tokenData = self::getTokenData();
        if ($tokenData['roles'] == AdminRoles::ADMIN OR $tokenData['roles'] == AdminRoles::SCHOOL) {
            return $tokenData['id'];
        }
        throw new BusinessException(ErrorCode::LOGIN_ERROR);
    }

    // 管理员ID
    public static function getAdminId()
    {
        $tokenData = self::getTokenData();
        if ($tokenData['roles'] == AdminRoles::ADMIN) {
            return $tokenData['id'];
        }
        throw new BusinessException(ErrorCode::LOGIN_ERROR);
    }

    // 学校账号ID
    public static function getSchoolAdminId()
    {
        $tokenData = self::getTokenData();
        if ($tokenData['roles'] == AdminRoles::SCHOOL) {
            return $tokenData['id'];
        }
        throw new BusinessException(ErrorCode::LOGIN_ERROR);
    }
}
